<template>
	<el-drawer :title="titleMap[mode]" v-model="visible" size="800px" destroy-on-close @closed="$emit('closed')">
		<div style="padding-left: 20px;padding-right: 20px">
			<el-form :model="form" label-width="110px" :rules="rules" ref="ruleForm">
				<el-form-item>
					<template #label>
						<span style="color:#f56c6c;margin-right: 4px;">*</span>选择商品
					</template>
					<el-button type="primary" size="small" icon="el-icon-shopping-cart" @click="selectGoods">选择商品</el-button>
				</el-form-item>
				<el-form-item>
					<template #label>
						<span style="color:#f56c6c;margin-right: 4px;">*</span>选择规格
					</template>
					<el-table
						ref="multipleTable"
						:data="bargainGoods"
						@row-click="handleSelectionChange"
						style="width: 100%">
						<el-table-column width="55" label="选择">
							<template #default="scope">
								<el-radio class="radio" v-model="templateSelection" :label="scope.row.id">&nbsp;</el-radio>
							</template>
						</el-table-column>
						<el-table-column v-for="(item,index) in tableHead" :label="item.label" :key="index">
							<template #default="scope">
								{{ scope.row.sku[item.property] }}
							</template>
						</el-table-column>
						<el-table-column
							label="图片">
							<template #default="scope">
								<img :src="scope.row.image" style="width: 40px;height: 40px"/>
							</template>
						</el-table-column>
						<el-table-column
							label="商品价格">
							<template #default="scope">
								{{ scope.row.goods_price }}
							</template>
						</el-table-column>
						<el-table-column
							label="首刀价格">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.first_cut_price"></el-input>
							</template>
						</el-table-column>
						<el-table-column
							label="底价价格">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.min_price"></el-input>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
				<el-form-item label="砍价标题" prop="name">
					<el-input v-model="form.name" placeholder="砍价标题" style="width: 500px" clearable></el-input>
				</el-form-item>
				<el-form-item label="活动起止时间" prop="activity_time">
					<div style="width: 500px">
						<el-date-picker
							style="width: 100%"
							v-model="form.activity_time"
							type="daterange"
							value-format="YYYY-MM-DD"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
						>
						</el-date-picker>
					</div>
				</el-form-item>
				<el-form-item label="购买方式" prop="buy_way">
					<el-radio :label="1" v-model="form.buy_way">砍到任意金额可购买</el-radio>
					<el-radio :label="2" v-model="form.buy_way">砍到底价价格才可购买</el-radio>
				</el-form-item>
				<el-form-item label="每人发起次数" prop="one_person_buy_limit" style="margin-bottom: 10px">
					<el-input v-model="form.one_person_buy_limit" type="number" style="width: 500px" clearable></el-input>
				</el-form-item>
				<span style="font-size: 12px;color: #999;margin-left: 110px">活动期间内，同一个活动商品允许用户发起的砍价次数</span>
				<el-form-item label="帮砍人数" prop="join_num" style="margin-bottom: 10px">
					<el-input v-model="form.join_num" type="number" style="width: 500px" clearable></el-input>人
				</el-form-item>
				<span style="font-size: 12px;color: #999;margin-left: 110px">需要多少人砍价成功</span>
				<el-form-item label="每刀金额" prop="one_cut_amount">
					<el-radio :label="1" v-model="form.one_cut_amount">每刀固定金额</el-radio>
					<el-radio :label="2" v-model="form.one_cut_amount">每刀任意金额</el-radio>
				</el-form-item>
				<el-form-item label="自己砍价" prop="self_cut">
					<el-radio :label="1" v-model="form.self_cut">允许</el-radio>
					<el-radio :label="2" v-model="form.self_cut">不允许</el-radio>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="visible = false">取 消</el-button>
				<el-button type="primary" @click="optSubmit('ruleForm')" :loading="loading">立即提交</el-button>
			</div>
		</template>
		<el-dialog
			class="goods-select"
			title=""
			v-model="goodsDialogVisible"
			width="70%">
			<goods-select @selected-goods="handleSelectedGoods" @close-dialog="goodsDialogVisible=false"></goods-select>
		</el-dialog>
	</el-drawer>
</template>

<script>
import goodsSelect from "@/components/goodsSingleSelect/index.vue";

export default {
	components: {
		goodsSelect
	},
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增砍价商品',
				edit: '编辑砍价商品',
				show: '查看'
			},
			bargainGoods: [],
			form: {
				id: 0,
				goods_id: 0,
				goods_rule: '',
				name: '',
				image: '',
				one_person_buy_limit: 1,
				buy_way: 1,
				join_num: 1,
				one_cut_amount: 1,
				activity_time: [],
				self_cut: 1,
				status: 1,
				final: [],
				rule: []
			},
			rules: {
				name: [
					{required: true, message: '请输入商品标题', trigger: 'blur'}
				],
				activity_time: [
					{required: true, message: '活动起止时间', trigger: 'blur'}
				],
				one_person_buy_limit: [
					{required: true, message: '每人发起次数', trigger: 'blur'}
				],
				buy_way: [
					{required: true, message: '购买方式', trigger: 'blur'}
				],
				join_num: [
					{required: true, message: '帮砍人数', trigger: 'blur'}
				],
				one_cut_amount: [
					{required: true, message: '每刀金额', trigger: 'blur'}
				],
				self_cut: [
					{required: true, message: '自己砍价', trigger: 'blur'}
				],
				status: [
					{required: true, message: '请选择是否开启', trigger: 'blur'}
				],
			},
			loading: false,
			goodsDialogVisible: false,
			tableHead: [],
			templateSelection: '', // 单选
			visible: false
		}
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		// 新增或编辑
		optSubmit(formName) {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					if (this.form.goods_rule == 2 && this.form.final.length == 0) {
						this.$message.error('请勾选砍价商品')
						return false
					}

					if (this.form.goods_rule == 1 && this.form.goods_id == '') {
						this.$message.error('请勾选砍价商品')
						return false
					}

					if (this.form.goods_rule == 1) {
						this.form.min_price = this.bargainGoods[0].min_price
						this.form.first_cut_price = this.bargainGoods[0].first_cut_price
						this.form.price = this.bargainGoods[0].goods_price
					} else {
						let sku2Info = new Map()

						this.bargainGoods.forEach(item => {
							sku2Info.set(item.sku.join('※'), {
								min_price: item.min_price,
								first_cut_price: item.first_cut_price
							})
						})

						this.form.final.forEach((item, index) => {
							let key = item.sku.join('※')
							this.form.final[index].min_price = sku2Info.get(key).min_price
							this.form.final[index].first_cut_price = sku2Info.get(key).first_cut_price
						})
					}

					this.loading = true
					let res;
					if (this.form.id) {
						res = await this.$API.bargain.edit.post(this.form)
					} else {
						res = await this.$API.bargain.add.post(this.form)
					}
					this.loading = false
					if (res.code == 0) {
						this.$message.success(res.msg)
						this.$emit('success')
					} else {
						this.$message.error(res.msg)
					}
				}
			});
		},
		// 选择商品弹层
		selectGoods() {
			this.goodsDialogVisible = true
		},
		// 选择
		handleSelectionChange(row) {
			this.form.goods_id = row.goods_id

			this.templateSelection = row.id
			this.form.final = [];
			this.form.final.push({
				sku: row.sku,
				image: row.image,
				goods_id: row.goods_id,
				goods_price: row.goods_price,
				first_cut_price: row.first_cut_price,
				min_price: row.min_price
			})
		},
		// 点击确定选择的商品
		async handleSelectedGoods(row) {
			this.form.name = row[0].name
			// 单规格
			if (row[0].spec == 1) {
				this.bargainGoods = [
					{
						image: row[0].pic,
						goods_id: row[0].id,
						goods_rule: '',
						goods_price: row[0].price,
						first_cut_price: 1,
						min_price: row[0].price
					}
				];

				this.form.goods_id = row[0].id
				this.form.goods_rule = 1
				this.tableHead = []
			} else { // 多规格
				this.form.goods_rule = 2
				let res = await this.$API.goodsRule.getRuleByGoodsId.get({goods_id: row[0].id})
				// 原始商品的rule
				this.form.rule = JSON.parse(res.data.ruleData.rule)
				this.makeRule(JSON.parse(res.data.ruleData.rule), res.data.extend, 1)
			}

			this.goodsDialogVisible = false
		},
		// 生成规则
		makeRule(preItem, extend, type) {
			let titleMap = [];
			this.bargainGoods = []
			preItem.forEach((item, index) => {
				let data = item.item.filter(function (s) {
					return s && s.trim();
				})
				if (item.title != '' && data.length > 0) {
					titleMap.push({label: item.title, property: index})
				}
			})

			if (type == 1) {
				extend.forEach(item => {
					this.bargainGoods.push({
						id: item.id,
						sku: item.sku.split('※'),
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.price,
						first_cut_price: 1,
						min_price: item.price
					})
				})
			} else {
				extend.forEach(item => {
					this.bargainGoods.push({
						id: item.id,
						sku: item.sku.split('※'),
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.goods_price,
						first_cut_price: item.first_cut_price,
						min_price: item.min_price
					})

					// 选中默认
					this.form.goods_id = item.goods_id

					this.templateSelection = item.id
					this.form.final = [];
					this.form.final.push({
						sku: item.sku.split('※'),
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.goods_price,
						first_cut_price: item.first_cut_price,
						min_price: item.min_price
					})
				})
			}

			this.tableHead = titleMap
		},
		// 表单注入数据
		async setData(row) {
			let data = JSON.parse(JSON.stringify(row))
			this.form = data
			this.form.activity_time = [data.start_time.split(' ')[0], data.end_time.split(' ')[0]];
			let res = await this.$API.bargain.getEditInfo.get({activity_id: data.id})
			if (res.code == 0) {
				this.form.once_buy_limit = data.once_buy_limit
				this.form.price = data.price
				if (row.goods_rule == 2) { // 多规格
					this.form.rule = JSON.parse(data.bargain_goods_rule)
					this.makeRule(JSON.parse(data.bargain_goods_rule), res.data.jsonInfo, 2)
				} else { // 单规格
					this.form.rule = []
					this.bargainGoods = []
					let item = res.data.jsonInfo[0]
					this.form.price = item.goods_price
					this.bargainGoods.push({
						id: item.id,
						sku: '',
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.goods_price,
						first_cut_price: item.first_cut_price,
						min_price: item.min_price
					})

					// 选中默认
					this.form.goods_id = item.goods_id

					this.templateSelection = item.id
					this.form.final = [];
					this.form.final.push({
						sku: item.sku.split('※'),
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.goods_price,
						first_cut_price: item.first_cut_price,
						min_price: item.min_price
					})
				}

				this.$nextTick(() => {
					this.bargainGoods.forEach(item => {
						this.$refs.multipleTable.toggleRowSelection(item);
					})
				})
			}
		}
	}
}
</script>

<style scoped>

</style>
